<?php

namespace app\common\command;

use app\common\model\Bill;
use app\common\model\BillTitle;
use app\common\model\Order;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Queue;

class OpenBill extends Command
{

    protected function configure()
    {
        $this->setName('open-bill');
    }

    protected function execute(Input $input, Output $output)
    {

        $list = Order::where(['bill_id'=>0,'order_status'=>['in',[Order::ORDER_STATUS_WAIT_COMMENT,Order::ORDER_STATUS_OK]],'audit_time'=>['lt',strtotime('-7 days')]])->select()->toArray();
        if (!empty($list)){
            foreach ($list as $v){
                if ($v['pay_amount'] <= 0)
                    continue;
                if ($v['bill_id'] > 0)
                    continue;
                $bill_info = Bill::where(['status'=>1,'member_id'=>$v['member_id'],'orderId'=>$v['id']])->find();
                if (empty($bill_info)){
                    //获取发票抬头
                    $bill_title_info = BillTitle::where(['member_id'=>$v['member_id']])->order('default desc')->find();
//                    if (empty($bill_title_info)){
//                        $bill_title_info = BillTitle::create(['buyerName'=>"个人",'type'=>0,'email'=>'','mobile'=>'','openBlank'=>'','buyerAccount'=>'','buyerAddress'=>'','buyerTel'=>'','buyerTaxNum'=>'','member_id'=>$v['member_id'],'default'=>1]);
//                    }
                    $bill_info = Bill::create([
                        'buyerName'=>$bill_title_info->buyerName ?? '个人',
                        'type'=>$bill_title_info->type ?? 0,
                        'buyerTaxNum'=>$bill_title_info->buyerTaxNum ?? '',
                        'bill_money'=>sprintf("%01.2f", $v['pay_amount']),
                        'email'=>$bill_title_info->email ?? '',
                        'mobile'=>$bill_title_info->mobile ?? '',
                        'openBlank'=>$bill_title_info->openBlank ?? '',
                        'buyerAccount'=>$bill_title_info->buyerAccount ?? '',
                        'buyerAddress'=>$bill_title_info->buyerAddress ?? '',
                        'buyerTel'=>$bill_title_info->buyerTel ?? '',
                        'member_id'=>$v['member_id'],
                        'status'=>1,
                        'orderNo'=>getOrderSn(),
                        'orderId'=>$v['id'],
                    ]);
                    Order::update(['bill_id'=>$bill_info->id],['id'=>$v['id'],'member_id'=>$v['member_id']]);
                }
                Queue::push(\app\job\Bill::class,['member_id'=>$v['member_id'],'bill_id'=>$bill_info->id],'message');
            }
        }
        $output->info("Opend Bill Successed!");
    }


}
